package cms.api.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.solr.common.util.NamedList;

import java.util.Map;
import java.util.Set;

/**
 * Solr客户端工具类
 *
 * @author heyingcheng
 * @email heyingcheng@ctvit.com.cn
 * @date 2019/6/23 9:17
 */
public class SolrClientUtils {

    /**
     * 格式化NamedList
     *
     * @param namedList NamedList
     * @return com.alibaba.fastjson.JSONObject
     * @author heyingcheng
     * @date 2019/6/23 21:14
     */
    public static JSONObject formatNamedList(NamedList namedList) {
        JSONObject jsonObject = new JSONObject();
        int size = namedList.size();
        for (int i = 0; i < size; i++) {
            Object val = namedList.getVal(i);
            if (val instanceof NamedList) {
                jsonObject.put(namedList.getName(i), formatNamedList((NamedList) val));
            } else {
                jsonObject.put(namedList.getName(i), namedList.getVal(i));
            }
        }
        return jsonObject;
    }

    /**
     * 格式化SolrMap
     *
     * @param solrMap SolrMap
     * @return com.alibaba.fastjson.JSONObject
     * @author heyingcheng
     * @date 2019/6/23 21:14
     */
    public static JSONObject formatSolrMap(Map<String, Object> solrMap) {
        JSONObject jsonObject = new JSONObject();
        Set<Map.Entry<String, Object>> entries = solrMap.entrySet();
        entries.forEach(entry -> {
            Object value = entry.getValue();
            if (value instanceof NamedList) {
                jsonObject.put(entry.getKey(), formatNamedList((NamedList) value));
            } else {
                jsonObject.put(entry.getKey(), value);
            }
        });
        return jsonObject;
    }

    /**
     * 转义查询字符
     *
     * @param s 查询字符
     * @author heyingcheng
     * @date 2019/6/27 14:17
     * @return java.lang.String
     */
    public static String escapeQueryChars(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // These characters are part of the query syntax and must be escaped
            if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':'
                    || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~'
                    || c == '*' || c == '?' || c == '|' || c == '&' || c == ';' || c == '/'
                    || Character.isWhitespace(c)) {
                sb.append('\\');
            }
            sb.append(c);
        }
        return sb.toString();
    }

}
